*Random group assignment within ind-location-yr
quietly sort order
gen random1=runiform()
sum random1

* switch to pooled
quietly bys S J T (random1): gen order2=_n 
quietly bys S J T (random1): gen RG=order2>_N/2

*Random groups
quietly egen JTR=group(J T RG)
quietly egen STR=group(S T RG)
quietly egen SJTR=group(S J T RG)

quietly egen tag_SJTR=tag(SJTR)
quietly egen tag_STR=tag(STR)

*Random-group weights (employment shares)
quietly bys SJT RG:egen emp_SJTR	=total(empl)
quietly bys JT RG:egen emp_JTR		=total(empl)

quietly bys ST RG: egen emp_STR		=total(empl)
quietly gen empshare_SJTR			=emp_SJTR/emp_STR

*Generate FEs (xi and tau) from micro data

*taus
quietly reghdfe lA [aw=empl], absorb(temp_tau_R=SJTR) keepsingletons
quietly reghdfe temp_tau_R  if tag_SJTR, absorb(JT) resid keepsingletons
quietly predict tau_Rb if e(sample), resid

*xi
quietly reghdfe tau_Rb [aw=empshare_SJT], absorb(xi_temp_R=STR)  keepsingletons
quietly reghdfe xi_temp_R if tag_STR, absorb(T) resid keepsingletons
quietly predict xi_Rb if e(sample), resid


*Manipulation to get random FEs on same rows

tempvar temp1 temp2
quietly bys SJT RG: egen `temp1'	=max(tau_Rb) if RG==0
quietly bys SJT: egen tau_Rb0		=max(`temp1') 
quietly bys SJT RG: egen `temp2'	=max(tau_Rb) if RG==1
quietly bys SJT: egen tau_Rb1		=max(`temp2') 


tempvar temp1 temp2
quietly bys ST RG: egen `temp1'=max(xi_Rb) if RG==0
quietly bys ST: egen xi_Rb0=max(`temp1') 
quietly bys ST RG: egen `temp2'=max(xi_Rb) if RG==1
quietly bys ST: egen xi_Rb1=max(`temp2')

quietly keep if RG==0
